//
//  HotViewcontroller.m
//  YSBEmployee
//
//  Created by developer on 2021/11/30.
//  Copyright © 2021 ysb. All rights reserved.
//

#import "YSBViewController.h"
#import <Masonry/Masonry.h>
#import <UIKit/UIKit.h>
#import <YYModel/YYModel.h>
#import <MJRefresh/MJRefresh.h>
#import "YSBWebViewController.h"


@interface YSBCancellationViewController : YSBViewController<UITextFieldDelegate>

@property (nonatomic, strong) UIScrollView *scrollView;

@property (assign, nonatomic) BOOL isRealName;

@property (strong, nonatomic) UILabel *titleLabel;

@property (strong, nonatomic) UITextField *nameTextField;

@property (strong, nonatomic) UIView *lineView;


@property (strong, nonatomic) UITextField *cardTextField;

@property (strong, nonatomic) UIView *lineView1;


@property (strong, nonatomic) UITextField *verificationCodeTextField;

@property (strong, nonatomic) UIView *lineView2;

@property (strong, nonatomic) UILabel *timerTitleLabel;//重新获取

@property (strong, nonatomic) UIButton *timerButton;

@property (strong, nonatomic) UIButton *nextButton;

@property (strong, nonatomic) NSTimer *timer;

@property (assign, nonatomic) NSInteger second;



@property (nonatomic, strong) UIButton *checkBtn;//勾选协议框按钮

@property (strong, nonatomic) UIImageView *checkImgView;

@property (assign, nonatomic) BOOL isCheckSelected;

@property (nonatomic, strong) YYLabel *protocolLabel;//协议文字



@end


@implementation YSBCancellationViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"注销账号";
    
    [self configuration];
    
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    
    
}


- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
}


#pragma mark - Configuration
- (void)configuration {
    
    self.second = 60;

    [self configurationUI];
    
    [self.nameTextField addTarget:self action:@selector(judgeNextBtnStatus:) forControlEvents:(1 << 17)];
    [self.cardTextField addTarget:self action:@selector(judgeNextBtnStatus:) forControlEvents:(1 << 17)];
    [self.verificationCodeTextField addTarget:self action:@selector(judgeNextBtnStatus:) forControlEvents:(1 << 17)];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFiledEditChanged:) name:UITextFieldTextDidChangeNotification object:self.nameTextField];

}

- (void)configurationUI {
    
    YSBUserData *data = [YSBUserData userData];
    self.isRealName = data.userInfo.has_certification_p;
        
    if (self.isRealName) {//已实名
        [self addSubViewsWithRealName];
    }
    else{
        [self addSubViewsWithNoRealName];
    }
    
    
}

#pragma mark - 定义颜色方法
- (UIColor *)resetHEXColor:(NSInteger)rgbValue {
    
   UIColor *tempColor = [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0];
    return tempColor;
    
}

//无实名的视图
- (void)addSubViewsWithNoRealName {
        
    self.view.backgroundColor = [self resetHEXColor:0xf5f5f5];
    [self.view addSubview:self.scrollView];
    
    //标题
    self.titleLabel.text = @"请点击获取注销验证码";
    [self.scrollView addSubview:self.titleLabel];
    
    //验证码
    CGRect tempFrame = CGRectMake(15, CGRectGetMaxY(self.titleLabel.frame) + 20, [[UIScreen mainScreen] bounds].size.width - 30 - 80, 60);
    self.verificationCodeTextField.frame = tempFrame;
    [self.scrollView addSubview:self.verificationCodeTextField];

    [self.scrollView addSubview:self.lineView2];
    
    //倒计时
    [self.scrollView addSubview:self.timerTitleLabel];

    //发送验证码
    [self.scrollView addSubview:self.timerButton];


    //协议
    [self.scrollView addSubview:self.checkImgView];

    [self.scrollView addSubview:self.protocolLabel];

    //提交注销
    [self.scrollView addSubview:self.nextButton];


}


//有实名的视图
- (void)addSubViewsWithRealName {
        
    self.view.backgroundColor = [self resetHEXColor:0xf5f5f5];
    [self.view addSubview:self.scrollView];

    //标题
    [self.scrollView addSubview:self.titleLabel];

    //姓名
    [self.scrollView addSubview:self.nameTextField];
    
    [self.scrollView addSubview:self.lineView];
    
    //身份证
    [self.scrollView addSubview:self.cardTextField];
    
    [self.scrollView addSubview:self.lineView1];
    
    //验证码
    [self.scrollView addSubview:self.verificationCodeTextField];

    [self.scrollView addSubview:self.lineView2];

    //倒计时
    [self.scrollView addSubview:self.timerTitleLabel];

    //发送验证码
    [self.scrollView addSubview:self.timerButton];

    //协议
    [self.scrollView addSubview:self.checkImgView];

    [self.scrollView addSubview:self.protocolLabel];


    //提交注销
    [self.scrollView addSubview:self.nextButton];



}



#pragma mark - UITextFieldDelegate
/**
 判断登录按钮状态
 
 @param textField 相应的textField
 */
- (void)judgeNextBtnStatus:(UITextField *)textField {
    NSString *nameStr = self.nameTextField.text;
    NSString *cardStr = self.cardTextField.text;
    NSString *codeStr = self.verificationCodeTextField.text;
    
    if (self.isRealName) {
        if (nameStr.length > 1 && cardStr.length == 18 && codeStr.length == 4) {
            self.nextButton.userInteractionEnabled = YES;
            self.nextButton.backgroundColor = [self resetHEXColor:0x1e8dff];
        } else {
            self.nextButton.userInteractionEnabled = NO;
            self.nextButton.backgroundColor = [self resetHEXColor:0xcccccc];
        }
    }
    else{
        if (codeStr.length == 4) {
            self.nextButton.userInteractionEnabled = YES;
            self.nextButton.backgroundColor = [self resetHEXColor:0x1e8dff];
        } else {
            self.nextButton.userInteractionEnabled = NO;
            self.nextButton.backgroundColor = [self resetHEXColor:0xcccccc];
        }
    }

}

//限制18位身份证号和姓名是汉字
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (textField == self.nameTextField) {//姓名
        
        if (range.length == 1 && string.length == 0) {
            return YES;
        }else if (self.nameTextField.text.length > 20 - 1) {
            return NO;
        }else{
            return YES;
        }
    }
    if (textField == self.cardTextField) {//身份证
        if (range.length == 1 && string.length == 0) {
            return YES;
        }else if (self.cardTextField.text.length > 18 - 1) {
            return NO;
        }else{
            return YES;
        }
    }
    if (textField == self.verificationCodeTextField) {//验证码
        if (range.length == 1 && string.length == 0) {
            return YES;
        }else if (self.verificationCodeTextField.text.length > 4 - 1) {
            return NO;
        }else{
            return YES;
        }
    }
    
    return YES;
}

  
- (void)textFiledEditChanged:(id)notification{
      
    UITextRange *selectedRange = self.nameTextField.markedTextRange;
    UITextPosition *position = [self.nameTextField positionFromPosition:selectedRange.start offset:0];
      
    if (!position) { // 没有高亮选择的字
        //过滤非汉字字符
        self.nameTextField.text = [self filterCharactor:self.nameTextField.text withRegex:@"[^\u4e00-\u9fa5]"];
          
        if (self.nameTextField.text.length >= 20) {
            self.nameTextField.text = [self.nameTextField.text substringToIndex:20];
        }
    }else { //有高亮文字
        //do nothing
    }
}
  
//根据正则，过滤特殊字符
- (NSString *)filterCharactor:(NSString *)string withRegex:(NSString *)regexStr{
    NSString *searchText = string;
    NSError *error = NULL;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexStr options:(1 << 0) error:&error];
    NSString *result = [regex stringByReplacingMatchesInString:searchText options:(1 << 1) range:NSMakeRange(0, searchText.length) withTemplate:@""];
    return result;
}



#pragma mark - Action
- (void)nextButtonClick:(UIButton *)btn {

    NSLog(@"点击了按钮");
    
    if (self.isCheckSelected == NO) {
        [ProgressHUD showError:@"请勾选已阅读用户注销协议"];
        return;
    }
    
    NSDictionary *parameter = @{};
    NSString *codeStr = self.verificationCodeTextField.text;
    if (self.isRealName) {
        NSString *nameStr = self.nameTextField.text;
        NSString *cardStr = self.cardTextField.text;
        
        if ([YSBCommonTool isBlankString:nameStr]) {
            [ProgressHUD showError:@"请输入您的姓名"];
            return;
        }
        if ([YSBCommonTool isBlankString:cardStr]) {
            [ProgressHUD showError:@"请输入您注册时的身份证号"];
            return;
        }
        if ([YSBCommonTool isBlankString:codeStr]) {
            [ProgressHUD showError:@"请输入验证码"];
            return;
        }
        parameter = @{@"real_name": nameStr,
                      @"id_card": cardStr,
                      @"code":codeStr
        };
    }
    else{
        if ([YSBCommonTool isBlankString:codeStr]) {
            [ProgressHUD showError:@"请输入验证码"];
            return;
        }
        parameter = @{@"code":codeStr};
    }
    
    [self requestCancellationWithDict:parameter];
    
}


- (void)logoutAction {
    
    [ProgressHUD showSuccess:@"注销成功"];

    [NSThread sleepForTimeInterval:0.5];
        
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"token"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"kIsLoginSuccess"];
    [YSBUserData clearUserData];
    
    //清除推送别名
    [LCJpushManage deleteAlias];
    
    [[YSBChatRoomWebSocketManager shared] webSocketClose];
    [[YSBJobChatWebSocketManager shared] webSocketClose];

    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [appDelegate faceStop];
        
    [[NSNotificationCenter defaultCenter] postNotificationName:@"logoutNotification" object:nil];
    appDelegate.window.rootViewController = [YSBTabBarController getTabBarControllerWithInfo:@""];
    
}


#pragma mark - 请求雇员注销接口
- (void)requestCancellationWithDict:(NSDictionary *)parameter {
    
    [[HttpClient sharedInstance] postURL:@"https://common.ysbjob.com/v1/staff/cancel" parameter:parameter success:^(id responseObject) {

        NSNumber *code = responseObject[@"status_code"];
        NSString *msg = responseObject[@"message"];
        
        if ([code intValue] == 200) {
            [self logoutAction];
        }
        else{
            [YSBCommonTool showSigleBtnAlertViewControllerWithTitle:msg andMessage:@"" andBtnTitle:@"知道了" andBtnAction:^(UIAlertAction *action) {

            }];
        }

    } failure:^(NSError *error) {
        
    }];
    
}


#pragma mark - 获取验证码
- (void)getCodeClick:(UIButton *)button {
    [self.view endEditing:YES];
    
    //重发短信验证码
    NSDictionary *parameter = @{@"type":@"user_cancel_code"};
    [[HttpClient sharedInstance] postURL:@"https://common.ysbjob.com/v1/user/code" parameter:parameter success:^(id responseObject) {

        NSNumber *code = responseObject[@"status_code"];
        if ([code intValue] == 200) {
            [ProgressHUD showSuccess:@"已发送验证码"];
            //开始倒计时
            self.second = 60;
            self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES]; //启动倒计时后会每秒钟调用一次方法 timeFireMethod
        }

    } failure:^(NSError *error) {
        button.userInteractionEnabled = YES;
    }];
    
}

- (void)timerAction {
    //倒计时-1
    self.second -= 1;
    //改动倒计时标签现实内容
    self.timerTitleLabel.text = [NSString stringWithFormat:@"(%ld秒)",self.second];
    self.timerTitleLabel.textColor = [self resetHEXColor:0x999999];
    self.timerButton.userInteractionEnabled = NO;
    //当倒计时到0时。做须要的操作，比方验证码过期不能提交
    if(self.second == 0){
        [self cancel];
    }
    
}


- (void)cancel {
    [self.timer invalidate];
    self.timerTitleLabel.text = @"重新获取";
    self.timerTitleLabel.textColor = [self resetHEXColor:0x1e8dff];
    self.timerButton.userInteractionEnabled = YES;
}



- (void)checkTouchTap:(UITapGestureRecognizer *)sender{
    self.isCheckSelected = !self.isCheckSelected;
    if (self.isCheckSelected) {
        self.checkImgView.image = [YSBCommonTool autoreleasepoolWithImageName:@"read_Check"];
    }
    else{
        self.checkImgView.image = [YSBCommonTool autoreleasepoolWithImageName:@"read_No_Check"];
    }
}



#pragma mark - Setter / Getter
- (UIScrollView *)scrollView {
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 1, [[UIScreen mainScreen] bounds].size.width, [[UIScreen mainScreen] bounds].size.height - 90)];
        _scrollView.backgroundColor = [UIColor whiteColor];
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.contentSize = CGSizeMake([[UIScreen mainScreen] bounds].size.width, self.scrollView.bounds.size.height + 230);
//        _scrollView.delegate = self;
    }
    return _scrollView;
}


- (UILabel *)titleLabel{
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 20, [[UIScreen mainScreen] bounds].size.width - 30, 30)];
        _titleLabel.textColor = [self resetHEXColor:0x333333];
        _titleLabel.font = [UIFont boldSystemFontOfSize:16];
        _titleLabel.numberOfLines = 0;
        _titleLabel.text = @"请在下方输入相关信息以核验是否为本人操作：";
        [_titleLabel sizeToFit];
    }
    return _titleLabel;
}


- (UITextField *)nameTextField{
    if (!_nameTextField) {
        _nameTextField = [[UITextField alloc] initWithFrame:CGRectMake(15, CGRectGetMaxY(self.titleLabel.frame) + 5, [[UIScreen mainScreen] bounds].size.width - 30, 60)];
        _nameTextField.placeholder = @"请输入您的姓名";
        _nameTextField.borderStyle = UITextBorderStyleNone;
        _nameTextField.delegate = self;
        _nameTextField.keyboardType = 0;
        _nameTextField.clearButtonMode = 1;
    }
    return _nameTextField;
}


- (UIView *)lineView{
    if (!_lineView) {
        _lineView = [[UIView alloc] initWithFrame:CGRectMake(15, CGRectGetMaxY(self.nameTextField.frame), [[UIScreen mainScreen] bounds].size.width - 30, 0.5)];
        _lineView.backgroundColor = [self resetHEXColor:0xe2e2e2];
    }
    return _lineView;
}



- (UITextField *)cardTextField{
    if (!_cardTextField) {
        _cardTextField = [[UITextField alloc] initWithFrame:CGRectMake(15, CGRectGetMaxY(self.nameTextField.frame), [[UIScreen mainScreen] bounds].size.width - 30, 60)];
        _cardTextField.placeholder = @"请输入您注册时的身份证号";
        _cardTextField.borderStyle = UITextBorderStyleNone;
        _cardTextField.delegate = self;
        _cardTextField.clearButtonMode = 1;
    }
    return _cardTextField;
}



- (UIView *)lineView1{
    if (!_lineView1) {
        _lineView1 = [[UIView alloc] initWithFrame:CGRectMake(15, CGRectGetMaxY(self.cardTextField.frame), [[UIScreen mainScreen] bounds].size.width - 30, 0.5)];
        _lineView1.backgroundColor = [self resetHEXColor:0xe2e2e2];
    }
    return _lineView1;
}


- (UITextField *)verificationCodeTextField{
    if (!_verificationCodeTextField) {
        _verificationCodeTextField = [[UITextField alloc] initWithFrame:CGRectMake(15, CGRectGetMaxY(self.cardTextField.frame), [[UIScreen mainScreen] bounds].size.width - 30 - 80, 60)];
        _verificationCodeTextField.placeholder = @"请输入验证码";
        _verificationCodeTextField.borderStyle = UITextBorderStyleNone;
        _verificationCodeTextField.keyboardType = 4;
        _verificationCodeTextField.inputAccessoryView = [self addToolbar];
        _verificationCodeTextField.clearButtonMode = 1;
        _verificationCodeTextField.delegate = self;
    }
    return _verificationCodeTextField;
}

- (UIView *)lineView2{
    if (!_lineView2) {
        _lineView2 = [[UIView alloc] initWithFrame:CGRectMake(15, CGRectGetMaxY(self.verificationCodeTextField.frame), [[UIScreen mainScreen] bounds].size.width - 30, 0.5)];
        _lineView2.backgroundColor = [self resetHEXColor:0xe2e2e2];
    }
    return _lineView2;
}


- (UILabel *)timerTitleLabel{
    if (!_timerTitleLabel) {
        _timerTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake([[UIScreen mainScreen] bounds].size.width - 15 - 80, CGRectGetMinY(self.verificationCodeTextField.frame) + 10, 80, 40)];
        _timerTitleLabel.font = [UIFont systemFontOfSize:15.0f];
        _timerTitleLabel.textColor = [self resetHEXColor:0x1e8dff];
        _timerTitleLabel.text = @"获取验证码";
        _timerTitleLabel.textAlignment = 2;
    }
    return _timerTitleLabel;
}


- (UIButton *)timerButton{
    if (!_timerButton) {
        _timerButton = [[UIButton alloc] initWithFrame:CGRectMake([[UIScreen mainScreen] bounds].size.width - 15 - 80, CGRectGetMinY(self.verificationCodeTextField.frame) + 10, 80, 40)];
        _timerButton.userInteractionEnabled = YES;
        [_timerButton addTarget:self action:@selector(getCodeClick:) forControlEvents:(1 <<  6)];
    }
    return _timerButton;
}


- (UIImageView *)checkImgView{
    if (!_checkImgView) {
        _checkImgView = [[UIImageView alloc] initWithFrame:CGRectMake(15, CGRectGetMaxY(self.verificationCodeTextField.frame) + 20, 20, 20)];
        self.isCheckSelected = NO;
        _checkImgView.image = [YSBCommonTool autoreleasepoolWithImageName:@"read_No_Check"];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(checkTouchTap:)];
        [_checkImgView addGestureRecognizer:tap];
        _checkImgView.userInteractionEnabled = YES;
    }
    return _checkImgView;
}


- (YYLabel *)protocolLabel {
    if (!_protocolLabel) {
        _protocolLabel = [[YYLabel alloc] initWithFrame:CGRectMake(15 + 20 + 5, CGRectGetMaxY(self.verificationCodeTextField.frame) + 20, [[UIScreen mainScreen] bounds].size.width - 30 - 20, 20)];
        NSString *originText = @"我已阅读并同意《用户注销协议》";
        NSMutableAttributedString  *text1 = [[NSMutableAttributedString alloc] initWithString:originText];
        text1.yy_font = [UIFont systemFontOfSize:14];
        text1.yy_alignment = NSTextAlignmentLeft;
        text1.yy_color = [self resetHEXColor:0x999999];
        [text1 yy_setColor:[self resetHEXColor:0x1e8dff] range:[originText rangeOfString:@"《用户注销协议》"]];
        
        __weak typeof(self) weakSelf = self;
        [text1 yy_setTextHighlightRange:[originText rangeOfString:@"《用户注销协议》"]//设置点击的位置
                                  color:[self resetHEXColor:0x1e8dff]
                        backgroundColor:[UIColor clearColor]
                              tapAction:^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect)
         {
            __strong id strongSelf = weakSelf;
            YSBWebViewController *vc = [[YSBWebViewController alloc] init];
            vc.titleStr = @"用户注销协议";
            vc.url = @"http://www.ysbjob.com/user_cancel.html";
            [strongSelf.navigationController pushViewController:vc animated:NO];
             
         }];
        
        
        _protocolLabel.userInteractionEnabled  = YES;
        _protocolLabel.numberOfLines  = 0;
        _protocolLabel.attributedText = text1;
        _protocolLabel.textVerticalAlignment   = 1;
        _protocolLabel.backgroundColor = [UIColor clearColor];
        
        
    }
    return _protocolLabel;
}


- (UIButton *)nextButton{
    if (!_nextButton) {
        _nextButton = [[UIButton alloc] initWithFrame:CGRectMake(15, CGRectGetMaxY(self.protocolLabel.frame) + 20, [[UIScreen mainScreen] bounds].size.width - 30, 49)];
        _nextButton.backgroundColor = [self resetHEXColor:0xcccccc];
        _nextButton.layer.cornerRadius = 5;
        _nextButton.layer.masksToBounds = YES;
        _nextButton.userInteractionEnabled = NO;
        [_nextButton setTitle:@"提交注销" forState:UIControlStateNormal];
        _nextButton.titleLabel.font = [UIFont systemFontOfSize:16.0f];
        [_nextButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_nextButton addTarget:self action:@selector(nextButtonClick:) forControlEvents:(1 <<  6)];
    }
    return _nextButton;
}



@end

